package com.team.RunsFast_Api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.team.RunsFast_Api.config.RedisKeyConfig;
import com.team.RunsFast_Api.config.SystemConfig;
import com.team.RunsFast_Api.dao.UserDao;
import com.team.RunsFast_Api.dao.UserLevelDao;
import com.team.RunsFast_Api.dao.UserMsgDao;
import com.team.RunsFast_Api.service.intf.UserLevelService;
import com.team.RunsFast_Api.util.JedisUtil;
import com.team.runsfast.entity.User;
import com.team.runsfast.entity.UserLevel;
import com.team.runsfast.entity.UserMsg;
import com.team.runsfast.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
@Service
public class UserLevelServiceImpl implements UserLevelService {

    private final UserLevelDao userLevelDao;
    private final UserMsgDao userMsgDao;
    private final UserDao userDao;

    public UserLevelServiceImpl(UserLevelDao userLevelDao, UserMsgDao userMsgDao, UserDao userDao) {
        this.userLevelDao = userLevelDao;
        this.userMsgDao = userMsgDao;
        this.userDao = userDao;
    }

    @Override
    @Transactional(rollbackFor = SQLException.class)
    public int updateLevel(long uid, long score) {
        UserLevel userLevel = userLevelDao.selectById(uid);
        //验证对象是否为空
        if (userLevel != null) {
            //改变积分
            userLevel.setScore(userLevel.getScore() + score);
            //判断积分是消费的还是获得的 消费等级经验不变 获得 等级经验也增加等量
            if (score > 0) {
                //积分为正 获得等量经验值
                userLevel.setExpire(userLevel.getExpire() + score);
                //经验发生变化后要进行判断等级是否可以晋级、
                if (userLevel.getExpire() > Math.pow(10, userLevel.getLevel() + 1)) {
                    //经验值足够晋级
                    userLevel.setLevelmsg(SystemConfig.levels[userLevel.getLevel()]);
                    userLevel.setLevel(userLevel.getLevel() + 1);
                    //提示晋级成功
                    userMsgDao.insert(new UserMsg(userLevel.getUid(), 2, "恭喜你，升级到" + userLevel.getLevelmsg() + "段位了"));
                }
            }else {
                //是扣除的积分时
                if(userLevel.getScore()<score){
                    //如果用户的当前积分小于要扣除的积分，则对当前的用户进行封号处理，将积分设置为0
                    userDao.updateById(userLevel.getUid(),2);
                    //查询用户的手机号
                    User user = userDao.selectById(userLevel.getUid());
                    //封号后解封需要转人工，并将token中的值进行删除，需要登录
                    JedisUtil.delKey(RedisKeyConfig.USER_PHONE+user.getPhone());
                }
            }
            return userLevelDao.updateById(userLevel);
        }
        return 0;
    }

    @Override
    public R queryAll() {
        return R.ok(userLevelDao.selectList(null));
    }

    @Override
    public R select(String token) {
        return R.ok(userLevelDao.selectOne(new QueryWrapper<UserLevel>().eq("uid",Long.parseLong(token))));
    }
}
